package org.wanda.pv.util;


import org.apache.el.parser.ParseException;
import org.json.JSONObject;
import org.nutz.dao.Cnd;
import org.nutz.http.Header;
import org.nutz.http.Response;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.wanda.pv.controller.file.FileUploadController;
import org.wanda.pv.framework.base.Result;
import org.wanda.pv.framework.utils.MyHttp;
import org.wanda.pv.model.hy.*;

import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

@SuppressWarnings("all")
public class HyUtil {
    private static InputStream resourceAsStream = HyUtil.class.getClassLoader().getResourceAsStream("application.properties");
    private static PropertiesProxy pp = new PropertiesProxy(resourceAsStream);
    public static String HY_API = pp.get("hy_api");
    private static Logger logger = LoggerFactory.getLogger(HyUtil.class);

    public static final String FIRSTCHECKINGPROJECT = "初审进行中…";
    public static final String FIRSTCHECKOVERPROJECT = "会审进行中…";
    public static final String REPETIONCHECKINGPROJECT = "复审进行中…";
    public static final String REPETIONCHECKOVERPROJECT = "项目审查结束…";
    public static final String WDROLENAME = "项目公司";
    public static final String DEROLENAME = "设计总包";
    public static final String PVROLENAME = "三审单位";

    // 同步2D 文件
    public static final String SYNC2DDRAW = HY_API + "/program/ws/v1/sync2dDraw";
    // 获取access_tokenD
    public static final String TOKEN_URL = HY_API + "/system/login";
    // 根据access_token 获取用户的id
    public static final String USERINFO_URL = HY_API + "/api-o/userInfo";
    // 根据用户id 获取用户详细信息
    public static final String INFOBYID_URL = HY_API + "/sys/user/v1/";
    // 获取用户用户的项目列表
    public static final String PROJECTLIST_URL = HY_API + "/project/provider/infoList/page";
	//获取用户在项目里的角色
    public static final String PROJECTROLELIST=HY_API + "/project/v1/projectRoleList/";
    // 获取项目信息
    public static final String PROJECTINFO_URL = HY_API + "/project/v1/";
    // 发送审核状态
    public static final String SENDPLANMSG = HY_API + "/program/ws/v1/sendPlanMsg";
    // 获取模型地图树
    public static final String TREE_URL = HY_API + "/program/v1/modelMap/tree";
    // 获取模型地图树关联的文件集合
    public static final String NODE_INFO = HY_API + "/program/v1/modelMap/tree/file";

    public static final String SEND_URL = HY_API + "/program/mq/send/ws";

    public static void sync2dDraw(String access_token,List<HySync2dDrawInfo>  hySync2DDrawInfos){
        Map<String, String> map = new HashMap<>();
        map.put("Content-Type", "application/json; charset=UTF-8");
        map.put("Authorization", "Bearer	" + access_token);
        Header jsonHeader = Header.create(map);
        Header header = Header.create(map);
        String json =  Json.toJson(hySync2DDrawInfos);
        Response response2 = MyHttp.postData(SYNC2DDRAW,json,header,1000);
        logger.info(response2.getContent()+"****");
    }

	public static HyRole getprojectRoleList(String access_token, String projectId, String userId) {
		Map<String, String> map = new HashMap<>();
		map.put("Authorization", "Bearer	" + access_token);
		Header header = Header.create(map);
		Response response = MyHttp.get(PROJECTROLELIST+projectId+"/"+userId,  header, 1000);
		logger.error(PROJECTROLELIST+projectId+"/"+userId);
		String content = response.getContent();
        logger.error(content);
		Map mp = (Map) Json.fromJson(content);
		String s = Json.toJson(mp.get("data"), JsonFormat.compact());
		logger.error(s);
		List<Object> list = (List<Object>) Json.fromJson(s);
        s = Json.toJson(list.get(0), JsonFormat.compact());
            map = (Map) Json.fromJson(s);
            HyRole hyRole=new HyRole();
            String name = getRoleType(map.get("name"));
            hyRole.setId(map.get("id"));
            hyRole.setName(map.get("name"));
            hyRole.setType(map.get("type"));
            String tmp=String.valueOf(map.get("status"));
            Integer status =Integer.parseInt(tmp);
            hyRole.setStatus(status );
            hyRole.setRoleType(name);

		return hyRole;

	}

    /**
     * 发送审核进度消息
     * @param access_token
     * @param projectFlowChildrenNodeId
     * @param params
     */
	public static  void sendPlanMessage(String access_token, String projectFlowChildrenNodeId,String params,String msgStatus){
        Map<String, String> map = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        map.put("Authorization", "Bearer	" + access_token);
        Header header = Header.create(map);
        param.put("msgStatus",msgStatus);
        param.put("projectFlowChildrenNodeId",projectFlowChildrenNodeId);
        param.put("params",params);
        Response response = MyHttp.post2(SENDPLANMSG,param,header,1000);
        String content = response.getContent();
        Map mp = (Map) Json.fromJson(content);
        String s = Json.toJson(mp.get("httpCode"), JsonFormat.compact());
        System.out.println("返回的 httpCode :"+s);
    }

	public static String getRoleType(String name){
		String roleType="";
		if (name.startsWith(PVROLENAME)){
			roleType = PVROLENAME;
		} else if (name.startsWith(WDROLENAME)){
			roleType = WDROLENAME;
		} else if (name.startsWith(DEROLENAME)){
			roleType = DEROLENAME;
		}
		return roleType;
	}

    public static List<HyDrawing> getDrawings(String access_token, String projectFlowChildrenNodeId, String modelMapTreeId) {
        Map<String, Object> param = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        map.put("Authorization", "Bearer	" + access_token);
        Header header = Header.create(map);
        param.put("modelMapTreeId", modelMapTreeId);
        param.put("projectFlowChildrenNodeId", projectFlowChildrenNodeId);
        Response response = MyHttp.get(NODE_INFO, param, header, 1000);
        String content = response.getContent();
        System.out.println(content);
        JSONObject jsonObject = new JSONObject(content);
        String data = jsonObject.get("data").toString();
        List<HyDrawing> hyDrawings = Json.fromJsonAsList(HyDrawing.class, data);
        return hyDrawings;

    }


    public static Boolean sendWS(String access_token, String projectFlowChildrenNodeId, int count) {
        try {
            Map<String, Object> param = new HashMap<>();
            Map<String, String> map = new HashMap<>();
            map.put("Authorization", "Bearer	" + access_token);
            Header header = Header.create(map);
            param.put("projectFlowChildrenNodeId", projectFlowChildrenNodeId);
            param.put("optionCount", count);
            Response response = MyHttp.get(SEND_URL, param, header, 1000);
            String content = response.getContent();
           // System.out.println(content);

            NutMap nutMap = Json.fromJson(NutMap.class, content);
            Integer httpCode = (Integer) nutMap.get("httpCode");
           // System.out.println(httpCode);
            if (httpCode != null && httpCode == 200)
                return true;
            return false;
        } catch (Exception e) {
            return false;
        }

    }

    public static List<HyTree> getTree(String access_token) {

        Map<String, Object> param = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        map.put("Authorization", "Bearer	" + access_token);
        Header header = Header.create(map);

        param.put("templateId", 1);
        // param.put("condition","draw");


        Response response = MyHttp.get(TREE_URL, param, header, 1000);
        String content = response.getContent();


        //====================
        Map mp = (Map) Json.fromJson(content);
        String s = Json.toJson(mp.get("data"), JsonFormat.compact());

        List<HyTree> hyTrees = Json.fromJsonAsList(HyTree.class, s);
        //====================
        return hyTrees;

    }


    public static HyProjectInfo getProjectInfo(String projectId, String access_token) {
        Map<String, String> map = new HashMap<>();
        map.put("Authorization", "Bearer	" + access_token);
        Header header = Header.create(map);
        Response response = MyHttp.get(PROJECTINFO_URL+projectId, header, 1000);
        String content = response.getContent();
        Map mp = (Map) Json.fromJson(content);
        String s = Json.toJson(mp.get("data"), JsonFormat.compact());
		map = (Map) Json.fromJson(s);
        HyProjectInfo hyProjectInfo =new HyProjectInfo();
        hyProjectInfo.setName(map.get("name"));
        hyProjectInfo.setCode(map.get("code"));
        hyProjectInfo.setId(map.get("id"));
        hyProjectInfo.setImgUrl(map.get("imgUrl"));
        hyProjectInfo.setProvince(map.get("province"));
        hyProjectInfo.setProjectForms(map.get("projectForms"));
        hyProjectInfo.setProjectModel(map.get("projectModel"));
        hyProjectInfo.setProjectType(map.get("projectType"));
        try {
            if (Strings.isNotBlank(map.get("delistingDate")))
            hyProjectInfo.setDelistingDate(dealDateFormat(map.get("delistingDate")));
            if (Strings.isNotBlank(map.get("projectTongbao")))
            hyProjectInfo.setProjectTongbao(dealDateFormat(map.get("projectTongbao")));

        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }

        return hyProjectInfo;


    }

    public static List<HyProjectSimple> getProjectList(String userId, String access_token) {
        Map<String, Object> param = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        map.put("Authorization", "Bearer	" + access_token);
        Header header = Header.create(map);
        param.put("userId", userId);
        Response response = MyHttp.get(PROJECTLIST_URL, param, header, 1000);
        String content = response.getContent();
       // System.out.println(content);
        JSONObject jsonObject = new JSONObject(content);
        JSONObject data = (JSONObject) jsonObject.get("data");
        String list = data.get("list").toString();
        //   System.out.println(list);

        List<HyProjectSimple> hyProjectSimples = Json.fromJsonAsList(HyProjectSimple.class, list);
        //  System.out.println(hyProjectSimples);
        return hyProjectSimples;
    }

    public static HyToken getHyToken() {
        Map<String, Object> param = new HashMap<>();

        Map<String, String> map = new HashMap<>();
        //map.put("Authorization","Basic dHJpbmFfYXBwOjU3ODhkYzRmNzBmMDBiMjU4NmExOWM5NQ==");
        //Header header = Header.create(map);
     /*   param.put("username", "admin");
        param.put("password", "oRFaq8j6ME1KQeTGC5RcMA==");*/
		param.put("username", "项目公司WS");
		param.put("password", "UhezYp1frc/DEMfYNkgUPg==");
        Response response = MyHttp.post2(TOKEN_URL, param, null, 1000);
        String content = response.getContent();
        HyToken hyToken = Json.fromJson(HyToken.class, content);
        return hyToken;
    }
    public static HyToken getHyTokenByUser(String username,String password) {
        Map<String, Object> param = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        param.put("username", username);
        param.put("password", password);
        Response response = MyHttp.post2(TOKEN_URL, param, null, 1000);
        String content = response.getContent();
        HyToken hyToken = Json.fromJson(HyToken.class, content);
        return hyToken;
    }

   /* public static HyUserSimple getUserSimple(String access_token){
        Map<String,Object> param = new HashMap<>();
        Map<String,String> map = new HashMap<>();
        map.put("Authorization","Bearer	"+access_token);
        Header header = Header.create(map);
        param.put("access_token",access_token);
        Response response = MyHttp.post2(USERINFO_URL, param, header, 1000);
        String content = response.getContent();
        HyUserSimple hy_userSimple = Json.fromJson(HyUserSimple.class, content);
        System.out.println(hy_userSimple.getId());
        return hy_userSimple;
    }*/

    public static String getUserSimple(String access_token) {
        String content = "";
        Map<String, Object> param = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        map.put("Authorization", "Bearer	" + access_token);
        Header header = Header.create(map);
        Response response = MyHttp.get(USERINFO_URL, param, header, 1000);

        content = response.getContent();
        logger.error(content);
        return content;
    }

    public static HyUserInfo getUserInfo(String id, String access_token) {
        Map<String, String> map = new HashMap<>();
        map.put("Authorization", "Bearer	" + access_token);
        Header header = Header.create(map);
        Response response = MyHttp.get(INFOBYID_URL+id, header, 1000);
        String content = response.getContent();
        Map mp = (Map) Json.fromJson(content);
        String s = Json.toJson(mp.get("data"), JsonFormat.compact());
        HyUserInfo hyUserInfo = new HyUserInfo();
        mp = (Map) Json.fromJson(s);
        hyUserInfo.setHyUserId((String) mp.get("id"));
        hyUserInfo.setEmail((String) mp.get("email"));
        hyUserInfo.setMobile((String) mp.get("mobile"));
        hyUserInfo.setLoginName((String) mp.get("loginName"));
        s=Json.toJson(mp.get("officeApiBody"), JsonFormat.compact());
        if (s != null ) {
            HyOffice hyOffice =Json.fromJson(HyOffice.class, s);
            hyUserInfo.setHyOffice(hyOffice);
            hyUserInfo.setHyOfficeId(hyOffice.getId());
        }
        return hyUserInfo;
    }

    public static void main(String[] args) throws java.text.ParseException {
    	//   {"data":[{"id":"1212","name":"设计总包 BIM负责人","type":"1212","status":1}],"httpCode":200,"sys_msg":"OK","timestamp":1545211481588}
		//    {"data":[{"id":"d55bb794f46f4de599ac7361bb96c7f4","name":"项目公司 BIM管理人员","type":"user","status":1}],"httpCode":200,"sys_msg":"OK","timestamp":1545211762947}
		//    {"data":[{"id":"4cc3b93fb5134246ba6e06aca828f580","name":"三审单位 BIM模型审核人员","type":"security-role","status":1}],"httpCode":200,"sys_msg":"OK","timestamp":1545211811848}
        HyToken hyToken=HyUtil.getHyTokenByUser("三审单位WS","UhezYp1frc/DEMfYNkgUPg==");  //  HyUtil.getHyTokenByUser("设计总包WS","UhezYp1frc/DEMfYNkgUPg==");
        System.out.println(hyToken.getAccess_token());
        getDrawings(hyToken.getAccess_token(),"890a471c7a674545942c640bd8b228e7","a7e0b32a3e554e52a602f4ded7cc84ee");
        getDrawings(hyToken.getAccess_token(),"890a471c7a674545942c640bd8b228e7","abefa8f7381b4068aa802841658f9ba1");
        getDrawings(hyToken.getAccess_token(),"890a471c7a674545942c640bd8b228e7","b8ba5558e047403fae14bc57ef607c96");
        getDrawings(hyToken.getAccess_token(),"890a471c7a674545942c640bd8b228e7","135");
        getDrawings(hyToken.getAccess_token(), "890a471c7a674545942c640bd8b228e7", "136");
        getDrawings(hyToken.getAccess_token(),"890a471c7a674545942c640bd8b228e7","137");
        String userId=HyUtil.getUserSimple(hyToken.getAccess_token());
		/*HyUtil.getprojectRoleList(hyToken.getAccess_token(),"51C6E0C9-6BB6-4DDC-8D16-298B398C2805",userId);
		sendPlanMessage(hyToken.getAccess_token(),"cba8c9b5f04a4fc2ac39475b5e3806fe","","初审进行中…");*/
    }
//  access_token_hy=5014ad51-0c68-4b22-93cf-19d0d2d092c3&projectFlowChildrenNodeId=890a471c7a674545942c640bd8b228e7&projectId=8C9C7D50-4AA7-4E6A-A622-6A082D179670

    /**
     * @throws ParseException
     */
    public static Date dealDateFormat(String oldDateStr) throws java.text.ParseException {
        String [] spdate=oldDateStr.split("T");
        String spdate1=spdate[1].substring(0,8);
        SimpleDateFormat sf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sf1.parse(spdate[0]+" "+spdate1);
        return date;
    }

    /**
     * 检查token的状态是否可用
     * @param token
     * @return
     */
    public static Object checkTokenStatus (String result,String token){
        Map<String,Object> resultMap = new HashMap<>();
        boolean status=true;
        String msg="";
        String errorInfo="{\"error\":\"invalid_token\",\"error_description\":\"Invalid access token: "+token+"\"}";
        String errorInfo2="{\"error\":\"invalid_token\",\"error_description\":\"Invalid access token: null\"}";
        // return Result.error("Token过期，请重新登录！","Token过期，请重新登录！");
        if (errorInfo.equals(result)){
            status = false;
            msg="Token过期，请重新登录！";
        } else if (errorInfo2.equals(result)){
            status = false;
            msg="Token不能为空！";
        }
        resultMap.put("status",status);
        resultMap.put("msg",msg);
        return resultMap;
    }
}
